<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 110px;
  line-height: 178px;
  text-align: center;
}
.top-div {
  width: 200px;
  height: 50px;
  position: relative;
}

.addButton {
  position: absolute;
  top: 3px;
  left: 98px;
  border-color: green;
}

.deleteButton {
  position: absolute;
  top: 3px;
  border-color: green;
}

.el-table--border th.el-table__cell, .el-table__fixed-right-patch {
  background-color: #333333;
  color: #ffffff;
}

.el-dialog__title {
  font-family: 黑体;
  font-size: 25px;
}

.el-dialog__header {
  text-align: center;
}

.el-form-item__label {
  font-size: 17px;
}

.formFoot {
  margin-left: -23px
}
</style>

<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }" style="font-size: 19px;">
        <i class="el-icon-s-home"></i> 个人中心
      </el-breadcrumb-item>
      <el-breadcrumb-item style="font-size: 17px">管理员管理</el-breadcrumb-item>
    </el-breadcrumb>

    <div style="margin: 24px 0 12px 0">
      <el-divider></el-divider>
    </div>

    <div class="top-div">
      <el-button size="medium" round class="addButton" icon="el-icon-circle-plus"
                 @click="addNewFormVisible = true">新增
      </el-button>
      <el-popconfirm
          @confirm="deleteNotices()"
          confirm-button-text='确定'
          cancel-button-text='取消'
          icon="el-icon-info"
          icon-color="red"
          title="确定要删除选中的管理员吗？">
        <el-button class="deleteButton" icon="el-icon-delete" round size="medium"
                   slot="reference">删除
        </el-button>
      </el-popconfirm>
    </div>

    <!--  表格  -->
    <el-table
        class="table"
        ref="multipleTable"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39"></el-table-column>
      <el-table-column prop="id" label="ID" width="100px" align="center"></el-table-column>

      <el-table-column prop="photo" header-align="center" align="center" label="图片" width="260">
        <template slot-scope="scope">
          <el-avatar :size="40"
                     :src="scope.row.avatar<1?'':require('../img/admin/'+scope.row.avatar)"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="admName" label="用户名" width="120" align="center" header-align="center"></el-table-column>
      <el-table-column prop="nickname" label="昵称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号码" header-align="center" align="center"></el-table-column>
      <el-table-column prop="email" label="电子邮箱" header-align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="description" label="简介" width="200px" header-align="center" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="是否启用" width="80" header-align="center" align="center">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.enable"
              @change="toggleEnable(scope.row)"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#cccccc">
          </el-switch>
        </template>
      </el-table-column>

      <!--操作-->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="success" icon="el-icon-edit" round size="small"
                     @click="openEditDialog(scope.row)">修改
          </el-button>
          <el-button type="danger" icon="el-icon-delete" round size="small"
                     @click="confirmDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--  弹出添加管理员的弹框  -->
    <el-dialog :destroy-on-close="true" style="" title="新增管理员" width="700px" :visible.sync="addNewFormVisible">
      <el-form :model="adminForm" :rules="rules" ref="adminForm" label-width="130px" class="demo-adminForm">

        <el-form-item label="用户名" prop="admName">
          <el-input v-model="adminForm.admName"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="admPassword">
          <el-input v-model="adminForm.admPassword"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="adminForm.nickname"></el-input>
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
              :on-remove="handleRemove"
              :limit="1"
              list-type="picture-card"
              class="avatar-uploader"
              action="http://localhost:8081/admin/upload"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload">
            <i class="el-icon-plus avatar-uploader-icon"></i v-else>
          </el-upload>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="adminForm.phone"></el-input>
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="adminForm.email"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="description">
          <el-input v-model="adminForm.description"></el-input>
        </el-form-item>

        <el-form-item label="是否启用">
          <el-switch
              v-model="adminForm.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#cccccc">
          </el-switch>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="adminForm.roleIds" multiple placeholder="请选择">
            <el-option
                v-for="item in RoleListOptions"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" style="background-color: #008000; border-radius: 30px"
                     @click="submitAddNewForm('adminForm')">添加
          </el-button>
          <el-button style="border-radius: 30px" @click="resetForm('adminForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  弹出修改管理员的弹框  -->
    <el-dialog :destroy-on-close="true" style="border-radius: 30px" :title="updateDialogTitle" :visible.sync="editFormVisible">
      <el-form :model="updateForm" :rules="rules" ref="updateForm" label-width="130px" class="demo-updateForm">

        <el-form-item label="用户名" prop="admName">
          <el-input v-model="updateForm.admName"></el-input>
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="updateForm.nickname"></el-input>
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
              :show-file-list="false"
              class="avatar-uploader"
              action="http://localhost:8081/admin/upload"
              :on-success="handleSuccess2"
              :before-upload="beforeAvatarUpload">
            <img v-if="updateForm.avatar"
                 :src="updatePhotoUrl!=''?updatePhotoUrl:require('../img/admin/'+updateForm.avatar)"
                 style="height: 110px;width: 150px;display: block"
                 class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="updateForm.phone"></el-input>
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="updateForm.email"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="description">
          <el-input v-model="updateForm.description"></el-input>
        </el-form-item>

        <el-form-item label="角色">
          <el-select v-model="updateForm.roleIds" multiple placeholder="请选择">
            <el-option
                v-for="item in RoleListOptions"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="formFoot">
          <el-button style="border-radius: 30px" @click="resetForm('updateForm')">重置</el-button>
          <el-button style="border-radius: 30px" @click="editFormVisible = false">取消</el-button>
          <el-button style="background-color: #008000; border-radius: 30px" type="primary"
                     @click="submitUpdateForm('updateForm')">修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <div style="margin-top: 10px;width: 100px">
      <el-button style="border-radius: 30px" @click="toggleSelection()">取消选择</el-button>
    </div>
    <!--  分页  -->
    <div class="block" align="center">
      <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page.sync="page"
          :page-size="pageSize"
          layout="prev, pager, next, jumper"
          :total="this.totalCount">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      updatePhotoUrl:'',
      totalCount: 0,
      addNewAdminUrl:'',
      pageSize: 5,
      page: 1,
      RoleListOptions: [],
      addNewFormVisible: false,
      editFormVisible: false,
      formLabelWidth: '50px',
      tableData: [],
      ids: [],
      multipleSelection: [],
      updateDialogTitle: '',
      adminForm: {
        admName: 'xiaoKai',
        admPassword: '管理员测试001',
        nickname: '小凯',
        avatar: '',
        phone: 1345678900,
        email: '@abc.com',
        description: '测试管理员描述1',
        roleIds: []
      },
      updateForm: {
        admName: '',
        nickname: '',
        avatar: '',
        phone: '',
        email: '',
        description: '',
        roleIds: []
      },
      rules: {
        admName: [
          {required: true, message: '请输入2-10位中文、英文、数字但不包括下划线等符号的用户名！', trigger: 'blur'},
        ],
        admPassword: [
          {required: true, message: '请输入8-18位包含英文、数字的密码！', trigger: 'blur'},
        ],
        nickname: [
          {required: true, message: '请输入2-10位中文、英文、数字但不包括下划线等符号的昵称！', trigger: 'blur'},
        ],
        phone: [
          {required: true, message: '手机号码格式不正确,请输入1-11位数字的手机号!', trigger: 'blur'},
        ],
        email: [
          {required: true, message: '请输入正确的邮箱格式！', trigger: 'blur'},
        ],
        description: [
          {required: true, message: '请输入2-50个字符的管理员描述！', trigger: 'blur'},
        ],
      }
    }
  },
  methods: {
    //撤销上传图片
    handleRemove(file, fileList) {
      console.log("需要移除的文件是"+file, fileList);
      console.log("需要移除的uuid值是"+file.response);
      let url = 'http://localhost:8081/admin/uploadDelete/uuid=' + file.response;
      console.log('执行图片撤销的请求路径是：'+url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.adminForm.avatar = '';
          this.$notify.success({
            title: '提示',
            message: '撤销图片成功！',
            showClose: true,
            position: 'top-right'
          });
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-right'
          });
        }
      });
    },

    //取消选择方法
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选择方法
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log('多选框数据是：' + JSON.stringify(this.multipleSelection));
    },
    handleCurrentChange(val) {
      this.page = val;
      this.loadAdminList();
      console.log(`当前页: ${val}`);
    },
    //图片上传成功后
    handleSuccess(response,file) {
      console.log(response);
      this.adminForm.avatar = response;
    },
    handleSuccess2(response,file) {
      console.log(response);
      this.updateForm.avatar = response;
      this.updatePhotoUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //执行多项删除
    deleteNotices() {
      (this.ids).length = 0;
      if ((this.multipleSelection).length == 0) {
        this.$notify.warning({
          title: '提示',
          message: '请选择管理员！',
          showClose: false,
          position: 'top-left'
        });
        return;
      }
      for (let data of this.multipleSelection) {
        this.ids.push(data.id);
      }
      console.log('ids是：' + JSON.stringify(this.ids))

      let url = 'http://localhost:8081/admin/deleteIds';
      console.log('批量删除管理员请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .post(url, this.ids).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$notify.success({
            title: '提示',
            message: '删除成功！',
            showClose: true,
            position: 'top-left'
          });
          this.loadAdminList();
        } else {
          this.$notify.warning({
            title: '提示',
            message: responseBody.message,
            showClose: true,
            position: 'top-left'
          });
          this.loadAdminList();
        }
      });
    },

    //展示管理员列表
    loadAdminList() {
      let url = 'http://localhost:8081/admin/' + this.page + '/' + this.pageSize + '/list';
      console.log('管理员列表展示请求的url是' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.tableData = responseBody.data.list;
          this.totalCount = responseBody.data.totalCount;
        } else {
          this.$notify.error({
            title: '提示',
            message: responseBody.message,
            showClose: false,
            position: 'top-left'
          });
        }
      })
    },

    //弹出确认删除框
    confirmDelete(admin) {
      console.log('尝试打开删除[id=' + admin.id + ']数据的对话框');
      let message = '此操作将永久删除【' + admin.admName + '】管理员, 是否继续?';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(admin);
      }).catch(() => {
      });
    },

    //执行删除
    handleDelete(admin) {
      let url = 'http://localhost:8081/admin/' + admin.id + '/delete';
      console.log("url = ", url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$notify.success({
            title: '提示',
            message: '删除【' + admin.admName + '】管理员成功！',
            showClose: false,
            position: 'top-right'
          });
          this.loadAdminList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        } else {
          this.$notify.error({
            title: '提示',
            message: responseBody.message,
            showClose: false,
            position: 'top-right'
          });
        }
      });
    },

    //执行启用或禁用
    toggleEnable(admin) {
      let enableText = ['禁用', '启用'];
      let url = 'http://localhost:8081/admin/' + admin.id + '/';
      if (admin.enable == 1) {
        url += 'enable';
      } else {
        url += 'disable';
      }
      console.log('url=' + url);

      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          let message = '操作成功，已经将【' + admin.admName
              + '】管理员的状态改为【' + enableText[admin.enable] + '】！';
          this.$notify.success({
            title: '提示',
            message: message,
            showClose: false,
            position: 'top-right'
          });
        } else {
          this.$notify.error({
            title: '提示',
            message: responseBody.message,
            showClose: false,
            position: 'top-right'
          });
          this.loadAdminList();
        }
      })
    },

    //展示角色列表
    loadRoleList() {
      let url = 'http://localhost:8081/role/list';
      console.log('url = ' + url);
      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.RoleListOptions = responseBody.data;
        }
      })
    },

    //执行添加管理员
    submitAddNewForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:8081/admin/addNew';
          console.log('URL = ' + url);
          let formData = this.qs.stringify(this.adminForm);
          console.log('formData = ' + formData);

          this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.$notify.success({
                title: '提示',
                message: "添加管理员成功！",
                showClose: false,
                position: 'top-right'
              });
              this.addNewFormVisible = false;
              this.loadAdminList();
            } else {
              this.$notify.error({
                title: '提示',
                message: responseBody.message,
                showClose: false,
                position: 'top-right'
              });
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //弹出修改框
    openEditDialog(admin) {
      console.log('尝试打开编辑[id=' + admin.id + ']数据的对话框');
      this.updateForm.avatar = admin.avatar;

      let url = 'http://localhost:8081/admin/getStandard/' + admin.id;
      console.log('url = ' + url);

      this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.updateDialogTitle = '修改【' + admin.admName + '】管理员';
          this.updateForm = responseBody.data;
          this.editFormVisible = true;
        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAdminList();
            }
          });
        }
      })
    },

    //提交修改
    submitUpdateForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = this.qs.stringify(this.updateForm);
          console.log(formData);

          let url = 'http://localhost:8081/admin/' + this.updateForm.id + '/update';
          console.log('URL = ' + url);

          this.axios.create({'headers': {'Authorization': localStorage.getItem('adminJwt')}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.updatePhotoUrl = '';
              this.$notify.success({
                title: '提示',
                message: "修改管理员信息成功！",
                showClose: false,
                position: 'top-right'
              });
              this.editFormVisible = false;
              this.loadAdminList();
            } else if (responseBody.state == 40400) {
              this.$alert(responseBody.message, '警告', {
                confirmButtonText: '确定',
                callback: action => {
                  this.editFormVisible = false;
                  this.loadAdminList();
                }
              });
            } else {
              this.$notify.error({
                title: '提示',
                message: responseBody.message,
                showClose: false,
                position: 'top-right'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //清空添加输入框
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
  mounted() {
    this.loadAdminList();
    this.loadRoleList();
  }
}
</script>

